<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title>Biscuit</title>
		<link rel="stylesheet" href="css/reset.css" />
		<link rel="stylesheet" href="css/space.css" />
		<link rel="stylesheet" href="css/font.css" />
		<style type="text/css">
		.tt{width: 1000px;}
		.fl{float: left;}
		</style>
		<script type="text/javascript" src="js/jquery-1.7.js"></script>
		<script type="text/javascript" src="js/jquery.socket.js"></script>
		<script type="text/javascript" src="js/tiny_mce/jquery.tinymce.js"></script>
		<script type="text/javascript">
		$(function() {
			var chat = {lastUsername: null, username: "<%=session.getAttribute("userId")%>"},
				userList;
			
			$("#textarea").tinymce({
				script_url : "js/tiny_mce/tiny_mce.js",

				// General options
				theme : "advanced",
				plugins : "autolink,lists,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template,advlist",

				// Theme options
				theme_advanced_buttons1 : "bold, italic, underline, sub, sup, justifyleft, justifycenter, justifyright,strikethrough, indent, outdent, hr, numlist, bullist, link, unlink, todocheckboxes, removeformat,enbutton_1,forecolor, fontselect, fontsizeselect",
				theme_advanced_buttons2 : "",
				theme_advanced_buttons3 : "",
				theme_advanced_font_sizes: "1,2,3,4,5,6,7",
				theme_advanced_fonts: "Times New Roman = times new roman, times;Arial = arial, helvetica, sans-serif;Courier New = courier new, courier;Georgia = georgia, palatino;Trebuchet = trebuchet ms, geneva;Verdana = verdana, geneva",
				theme_advanced_more_colors: false,
				theme_advanced_toolbar_location : "top",
				theme_advanced_toolbar_align : "left",
				
				// Options for evernote
				allow_html_in_named_anchor: true,
				convert_urls: false,
				element: "DIV",
				extended_valid_elements: "img[longdesc|usemap|src|border|alt=|title|hspace|vspace|width|height|align|name|style],noembed,br[style|clear],div[id|class|style|title|dir<ltr?rtl|lang|xml::lang|onclick|ondblclick|onmousedown|onmouseup|onmouseover|onmousemove|onmouseout|onkeypress|onkeydown|onkeyup]",
				forced_root_block: "div",
				ie7_compact: true,
				indent: "simple",
				indent_after: "p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,ul,li,area,table,thead,tfoot,tbody,tr",
				indent_before: "p,h1,h2,h3,h4,h5,h6,blockquote,div,title,style,pre,script,td,ul,li,area,table,thead,tfoot,tbody,tr",
				mode: "exact",
				paste_block_drop: true,
				paste_convert_middot_lists: true,
				paste_retain_style_properties: "margin, padding, width, height, font-size, font-weight, font-family, color, text-align, ul, ol, li, text-decoration, border, background, float, display",
				plugins: "-todocheckboxes, -enlinks, lists, paste, safari,-enbutton_1_plugin",
				remove_trailing_brs: true,
				root_name: "body",
				valid_children: "+button[a], +ul[ul|ol], +ol[ul|ol]",
				setup: function(editor) {
					var changedNode = $("<p />")[0];
					
					$.socket("app")
					.on("entrance", function(id) {
						userList.push({id: id});
						setUserList();
					})
					.on("exit", function(id) {
						$.each(userList, function(i, val) {
							if (val.id == id) {
								userList.splice(i, 1);
								return false;
							}
						});
						setUserList();
					})
					.on("note", function(data) {
// 						saveSelection();
						$("#textarea").html(data);
// 						$("#textarea_ifr").contents().find("body").html(data);
// 						restoreSelection();
					})
					.on("chat", function(data) {
						var content = $("#content")[0];
						
						if (chat.lastUsername !== data.username) {
							chat.lastUsername = data.username;
							$('<p class="user"/>').text(data.username).appendTo(content);
						}
						
						$('<p class="message"/>').text(data.message).appendTo(content);
						content.scrollTop = content.scrollHeight;
					})
					.send("init", "<%=session.getAttribute("userId")%>" + location.search, function(room) {
						userList = room.userList;

						$("#timeMachineLink").click(function() {
							window.location = "timemachine.html?index=" + room.index;
						});
						
						setUserList();
						editor.onChange.add(function(editor) {
							$.socket().send("note", $("#textarea").html());
// 							$.socket().send("note", $("#textarea_ifr").contents().find("body").html());
						});
						editor.onKeyUp.add(function(editor) {
							$.socket().send("note", $("#textarea").html());
// 							$.socket().send("note", $("#textarea_ifr").contents().find("body").html());
						});
					});
					
					function setUserList() {
						$("#userCount").text(userList.length);
						$("#userList").empty();
						var users = [];
						$.each(userList, function(i, user) {
							users.push(user.id);
							$("<li />").text(user.id).appendTo("#userList");
						});
						$("#userList").attr("alt", users.join(",")).attr("title", users.join(","));
					}
				}
			});
			
			$("#editor .message").keyup(function(event) {
				if (event.which === 13 && $.trim(this.value)) {
					$.socket().send("chat", {username: chat.username, message: this.value});
					this.value = "";
				}
			});
			$(window).on("beforeunload", function() {
				$.socket().send("klose", "");
			});
		});
		</script>
		<script type="text/javascript">
		// http://stackoverflow.com/questions/1181700/set-cursor-position-on-contenteditable-div
		var savedRange;
		
		function saveSelection() {
			var win = $("#textarea_ifr")[0].contentWindow, doc = win.document;
			
			if (win.getSelection) {
				savedRange = win.getSelection().getRangeAt(0);
			} else if (doc.selection) { 
				savedRange = doc.selection.createRange();  
			}
		}
		
		function restoreSelection() {
			var win = $("#textarea_ifr")[0].contentWindow, doc = win.document;
			
			doc.body.focus();
			if (savedRange != null) {
				// //non IE and there is already a selection
				if (win.getSelection) {
					var s = win.getSelection();
					if (s.rangeCount > 0) {
						s.removeAllRanges();
					}
					s.addRange(savedRange);
					//non IE and no selection
				} else if (doc.createRange) {
					win.getSelection().addRange(savedRange);
					//IE
				} else if (doc.selection) {
					savedRange.select();
				}
			}
		}
		
		function exit() {
			if (confirm("Would you like to <SAVE> this note?")) {
				
				$.socket().send("exitroom", {
					accessToken: "<%=session.getAttribute("accessToken")%>",
					shardId: "<%=session.getAttribute("shardId")%>",
					share: confirm("Do you want to <SHARE> this note?")
				});
			}
			window.location = "list.html";
		}
		</script>
		<style>
		.user {font-size: 1.05em; font-weight: bold; letter-spacing: -1px;}
		#textarea {height: 100%;}
		</style>
	</head>
	<body>
	<div>
	<div style="width: 636px;">
		<form action="#" onsubmit="return false;">
			<textarea id="textarea" name="textarea" rows="30" class="tinymce"></textarea>
		</form>
		<button id="timeMachineLink">Go to timemachine!</button>
	</div>
	<div class="wrap_s fl">
		<div class="cp"><span>Connect : <span id="userCount"></span></span></div>
		<a href="javascript:exit()" class="lo"><img src="img/btn_1.png" alt="나가기" /></a>
		<div class="un">
			<span>UserName : </span>
			<ul id="userList">
			</ul>
		</div>
		<form action="#" onsubmit="return false;">
			<div id="content" class="tt_ar"></div>
			<div id="editor"><input type="text" class="message chat" name="chat" /></div>
		</form>
	</div>
	</div>
	</body>
</html>